<?php

class openapi_api_function_v1_cart extends openapi_api_function_abstract implements openapi_api_function_interface{

    function __construct(){
        parent::__construct();
        $this->mCart = app::get('b2c')->model('cart');
        $this->member_status = $this->checklogin();
    }


    private function toAdd($params,&$code,&$msg,&$res){

        $data = $params;
        $type = $params['cart_type']?$params['cart_type']:'goods';
        /**
         * 处理信息和验证过程
         */
        $arr_objects = array();
        if ($objs = kernel::servicelist('b2c_cart_object_apps'))
        {
            foreach ($objs as $obj)
            {
                if ($obj->need_validate_store()){
                    $arr_objects[$obj->get_type()] = $obj;
                }
            }
        }

        // 校验各自的数据是否可以加入购物车
        if (!$arr_objects[$type])
        {
            $msg = app::get('b2c')->_('加入购物车类型错误！');
            return false;
        }

        // 处理加入购物车商品的数据
        if (method_exists($arr_objects[$type], 'get_data')){
            if (!$aData = $arr_objects[$type]->get_data($data,$msg))
            {
                return false;
            }
        }
        // 校验加入购物车数据是否符合要求-各种类型的数据的特殊性校验
        if (method_exists($arr_objects[$type], 'check_object'))
        {
            if (!$arr_objects[$type]->check_object($aData,$msg))
            {
                return false;
            }
        }

        // 检查购物车库存数量
        $obj_cart_object = kernel::single('b2c_cart_objects');
        if (!$obj_cart_object->check_store($arr_objects[$type], $aData, $msg))
        {
            return false;
        }

        //begin  获取商品是否是限时抢购的商品  限时抢购的商品不能加入购物车
        $checkTimedbuy = kernel::service('timedbuy_check_goods_isTimedbuy');
        if($checkTimedbuy){
            if(!$checkTimedbuy->check_isTimedbuy($aData,$msg)){
                return false;
            }
        }
        //秒杀商品不能加入购物车
        $checkSpike = kernel::service('spike_check_goods_isSpike');
        if($checkSpike){
            if(!$checkSpike->check_isSpike($aData,$msg)){
                return false;
            }
        }

        $memberInfo = $this->get_member_info();

        //检查是否具有购买权限
        $check_objects = kernel::servicelist('business_check_goods_isMy');
        if($check_objects && $type!='coupon'){
            foreach($check_objects as $check_object){
                //验证购买权限
                if (method_exists($check_object, 'check_buy_power')) {
                    $check_object->check_buy_power($aData['goods'],$memberInfo,$msg,$sign);
                }
            }
            if(!$sign){
                return false;
            }
        }

        // 购物车中是否有虚拟物品
        $now_object = $this->mCart->get_objects();
        if(isset($now_object['object']['goods']['0']) && $type == 'goods'){
            $goods_id = $now_object['object']['goods']['0']['obj_items']['products']['0']['goods_id'];
            $check_objects = kernel::servicelist('business_check_goods_isMy');
            if($check_objects){
                foreach($check_objects as $check_object){
                    $check_object->check_goods_entity($aData['goods']['goods_id'],$goods_id,$msg,$sign);
                }
                if(!$sign){
                    return false;
                }
            }
        }

        //快速购买
        // if(isset($aData[1]) && $aData[1] == 'quick' && empty($this->member_status)){
        //     $this->redirect(array('app'=>'b2c','ctl'=>'site_cart','act'=>'checkout'));
        // }
        
        // 加入购物车
        if(!$obj_ident = $obj_cart_object->add_object($arr_objects[$type], $aData, $msg)){
            return false;
        } else {
            if(isset($aData[1]) && $aData[1] == 'quick') {
                if(!$this->member_status && !$_COOKIE['ST_ShopEx-Anonymity-Buy']){
                    return;
                }
                $this->checkout();
            }else{
                if($params['mini_cart']){
                    if($data['replenishment'][$aData['goods']['goods_id']][$aData['goods']['product_id']]){
                        $msg = app::get('b2c')->_('操作成功');
                        return true;
                    }else{
                        $arr = $this->mCart->get_objects();
                        $temp = $arr['_cookie'];
                        $this->pagedata['cartCount']      = $temp['CART_COUNT'];
                        $this->pagedata['cartNumber']     = $temp['CART_NUMBER'];
                        $this->pagedata['cartTotalPrice'] = $temp['CART_TOTAL_PRICE'];
                        return true;
                    }
                }
                // coupon
                if($aData[0]=='coupon'){
                    $this->_common(1);
                    //使用失败从购物车删除
                    $res_msg = '优惠券不适用';
                    foreach ($this->pagedata['aCart']['object']['coupon'] as &$cv) {
                        //活动商品不可使用优惠券
                        if($this->pagedata['aCart']['is_group'] || $this->pagedata['aCart']['is_spike'] || $this->pagedata['aCart']['inAct'] || $this->pagedata['aCart']['prepare']){
                            $cv['used'] = false;
                            $res_msg = '活动商品不可使用优惠券';
                        }
                        if(!$cv['used']){
                            app::get('b2c')->model('cart_objects')->remove_object('coupon', $cv['obj_ident'], $msg);
                        }
                    }
                    $arr_json_data = array(
                        'success'=>app::get('b2c')->_($res_msg),
                        'data'=>$this->pagedata['aCart']['object']['coupon'],
                        'md5_cart_info'=>kernel::single('b2c_cart_objects')->md5_cart_objects(),
                    );
                    $res = $arr_json_data;
                    return true;
                } else {
                    return true;
                }
            }
        }
    }

    public function add($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(!$member_id){
            return $this->apiData(false,null,301,app::get()->_('请登录'));
        }
        $storeinfo = kernel::single('business_storeinfo')->get();
        $params[0] = $params['cart_type']?$params['cart_type']:'goods';
        //整理加入购物车数据
        if($params[0]=='goods'){
            $params['goods']['num'] = $params['num'];
            $params['goods']['goods_id'] = $params['goods_id'];
            $params['goods']['pmt_id'] = $params['pmt_id'];
            $params['goods']['product_id'] = $params['product_id'];
            $params['mini_cart'] = true;
        }
        unset($_SESSION['replenishment']);
        if(isset($params['ass_store_id']) && !empty($params['ass_store_id']) && $params['ass_store_id']!=$storeinfo['sup_store_id']){
            if(intval($params['num'])>0){
                //判断购物车中的数据是否有其他经销商
                $cart_objects_cnt = app::get('b2c')->model('cart_objects')->count(array('member_id'=>$member_id));
                $cart_replenishment_cnt = app::get('b2c')->model('cart_objects_replenishment')->count(array('member_id'=>$member_id));
                if($cart_replenishment_cnt==0 && $cart_objects_cnt>0){
                    return $this->apiData(false,null,400,app::get('b2c')->_('请先提交订单或清空购物车'));
                }else{
                    $cart_replenishment = app::get('b2c')->model('cart_objects_replenishment')->count(array('member_id'=>$member_id,'store_id|noequal'=>$params['ass_store_id']));
                    if($cart_replenishment>0){
                        return $this->apiData(false,null,400,app::get('b2c')->_('请先提交订单或清空购物车'));
                    }
                }
                $_SESSION['replenishment'][$params['goods_id']][$params['product_id']][$params['ass_store_id']] = $params['num'];
            }else{
                return $this->apiData(false,null,400,app::get('b2c')->_('加入购物车数量有误'));
            }
        }
        $cart_replenishment = app::get('b2c')->model('cart_objects_replenishment')->count(array('member_id'=>$member_id));
        if($cart_replenishment>0){
            return $this->apiData(false,null,400,app::get('b2c')->_('请先提交订单或清空购物车'));
        }
        if(!$this->toAdd($params, $code, $sub_msg,$res)){
            $code = 400;
            return $this->apiData(false,$res,$code,$sub_msg);
        }else{
            $now_cart = app::get('b2c')->model('cart')->get_objects();
            //购物车显示项目数或者商品数
            $cart_show_type = app::get('site')->model('widgets_instance')->getRow('params',array('widgets_type'=>'index_cart'));
            if($cart_show_type['params']['cart_show_type']=='2'){
                $now_cart['_cookie']['CART_NUMBER'] = $now_cart['_cookie']['CART_COUNT'];
            }
            return $this->apiData(true,$now_cart['_cookie'],200,app::get('b2c')->_('成功加入购物车'));
        }
    }

    /**
     * 使用优惠券
     * @param
     * @return
     * @author hmg
     **/
    public function useCoupons($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(!$member_id){
            return $this->apiData(false,null,301,app::get()->_('请登录'));
        }
        $storeinfo = app::get('business')->model('storemanger')->getRow('*',array('account_id'=>$member_id));
        $params[0] = 'coupon';
        $params['cart_type'] = 'coupon';
        $params['store_id'] = $storeinfo['parent_id'];
        $params['split_order'] = urldecode($params['split_order']);
        $params['response_type'] = true;
        if(!$params['isdel']){
            if($this->toAdd($params,$code,$sub_msg,$res)){
                $this->shippingChangeSplit($params,$result);
                if($res['data'][0]['used']){
                    return $this->apiData(true,$result,200,app::get('b2c')->_('优惠券使用成功！'));
                }else{
                    return $this->apiData(false,$result,400,$res['success']);
                }
            }else{
                return $this->apiData(false,null,$code,$sub_msg);
            }
        }else{
            //删除优惠券
            $mCartObject = app::get('b2c')->model('cart_objects');
            $mCartObject->delete_store_coupon($params['store_id']);
            if($this->shippingChangeSplit($params,$result)){
                return $this->apiData(true,$result,200,app::get('b2c')->_('优惠券删除成功！'));
            }else{
                return $this->apiData(false,null,400,app::get('b2c')->_('优惠券删除失败'));
            }
        }
    }

    function shippingChangeSplit($params,&$result){
        $post=$params;
        $this->_common(0,$err_msg,$res);
        $this->pagedata = $res;
        // 购物车是否为空
        if ($this->pagedata['is_empty'])
        {
            $result = '';
            return false;
        }
        $defaule_area_id = explode(':',$params['area']);
        $area_id= $defaule_area_id[2];
        kernel::single('b2c_cart_object_split')->split_order($this,$area_id,$this->pagedata['aCart']);
        if ($this->pagedata['aCart']['json_order_split']!=$post['split_order'])
        {
            $result = '';
            return false;
        }
        $objCurrency = app::get('ectools')->model('currency');
        $split_order=unserialize($post['split_order']);
        $store_id=$post['store_id'];
        $is_protect=empty($post['is_protect'])?array():$post['is_protect'];
        $slips=$split_order[$store_id]['slips'];
        $result['store_subtotal']=$this->pagedata['aCart']['subtotal_store_good_price'][$store_id];

        foreach($slips as $key=>$slip){
           foreach($slip['shipping'] as $skey=>$ship){
               if(in_array($skey,$is_protect)){                   
                    if($this->pagedata['aCart']['is_free_shipping'][$store_id]==1){
                        $this->pagedata['discount'][$store_id]+=$ship['protect_money'];
                    }
                    $result['store_subtotal']+=$ship['protect_money'];
               }
               if(in_array($skey,$post['store_shipping'])){
                    if($this->pagedata['aCart']['is_free_shipping'][$store_id]==1){
                        $this->pagedata['discount'][$store_id]+=$ship['money'];
                    }
                    $result['store_subtotal']+=$ship['money'];
                    $result['shipping']['slips'][$key][$skey]['money']=$objCurrency->amount($ship['money']);
                    $result['shipping']['slips'][$key][$skey]['project']=$ship['protect'];
               }
           }
        }
        if($result['store_subtotal']-$this->pagedata['discount'][$store_id]<=0){
            $result['store_subtotal']=$objCurrency->amount(0);
        }else{
            $result['store_subtotal']=$result['store_subtotal']-$this->pagedata['discount'][$store_id];
        }
        $result['discount']= $this->pagedata['discount'][$store_id];
        return true;
    }

    public function addList($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(!$member_id){
            return $this->apiData(false,null,301,app::get()->_('请登录'));
        }
        $db = kernel::database();
        $transaction = $db->beginTransaction();
        foreach ($params['content'] as $key => $value) {
            $res = $this->toAdd($value, $code, $sub_msg);
            if(!$res){
                $db->rollback();//todo 事务不能完全回滚
                return $this->apiData(false,$value,400,$sub_msg);
            }
        }
        $db->commit($transaction);
        $now_cart = app::get('b2c')->model('cart')->get_objects();
        //购物车显示项目数或者商品数
        $cart_show_type = app::get('site')->model('widgets_instance')->getRow('params',array('widgets_type'=>'index_cart'));
        if($cart_show_type['params']['cart_show_type']=='2'){
            $now_cart['_cookie']['CART_NUMBER'] = $now_cart['_cookie']['CART_COUNT'];
        }
        return $this->apiData(true,$now_cart['_cookie'],200,app::get('b2c')->_('成功加入购物车'));
    }

    /**
     * 获取下级经销商价格
     * @param
     * @return
     **/
    public function getgradeprice($goods_id,$product_id,$grade_id){
        $subgrade_id = app::get('business')->model('storegrade')->getList('grade_id',array('parent_id'=>$grade_id));
        // 对经销商的商品价格和最低购买限制
        $objLimit = app::get('b2c')->model('goods_price_grade_limit');
        $limit_data = $objLimit->getData($goods_id,$product_id,$subgrade_id[0]['grade_id']);
        if(empty($limit_data[0]['limit_price'])){
            $store_limit = app::get('b2c')->model('goods_store')->getList("price",array('goods_id'=>$goods_id,"product_id"=>$product_id,'store_grade'=>$subgrade_id[0]['grade_id']));
            $limit_data[0]['limit_price'] = $store_limit[0]['price'];
        }
        return $limit_data[0]['limit_price'];
    }

    /**
     * 获取购物车列表
     * @param
     * @return
     **/
    public function cartlist($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(!$member_id){
            return $this->apiData(false,null,301,app::get()->_('请登录'));
        }
        $storemanger = app::get('business')->model('storemanger')->getList('store_id,store_grade,parent_id',array('account_id'=>$member_id));
        $now_cart = app::get('b2c')->model('cart')->get_objects();
        $goods = $now_cart['object']['goods'];
        if(empty($goods)){
            return $this->apiData(false,null,400,app::get('b2c')->_('购物车为空'));
        }
        foreach ($goods as $gk => $gv) {
            $p = $gv['obj_items']['products'][0];
            $g['goods_id'] = $p['goods_id'];
            $g['product_id'] = $p['product_id'];
            $g['goods_type'] = $p['goods_type'];
            $g['bn'] = $p['bn'];
            $g['name'] = $p['name'];
            $g['buy_price'] = $p['price']['buy_price'];
            $g['mktprice'] = number_format(round($p['price']['buy_price']*1.5),2,".","");
            $g['thumbnail'] = $p['thumbnail'];
            $g['new_name'] = $p['new_name'];
            $g['url'] = $p['url'];
            $g['store'] = $p['store'];
            $g['quantity'] = $gv['quantity'];
            $g['store_id'] = $gv['store_id'];
            $g['store_name'] = $gv['store_name'];
            $g['shop_name'] = $gv['shop_name'];
            $g['obj_ident'] = $gv['obj_ident'];
            $g['obj_type'] = $gv['obj_type'];
            $g['min_buy'] = $gv['min_buy']['min_buy'];
            $g['subtotal_price'] = $gv['subtotal_price'];
            //是否已加入心愿单
            $fav = app::get('b2c')->model('member_goods')->getRow('*',array('goods_id'=>$g['goods_id'], 'member_id'=>$member_id));
            $g['fav'] = empty($fav) ? false : true;
            //下级经销商价格限制
            $g['sub_store_price'] = $this->getgradeprice($p['goods_id'],$p['product_id'],$storemanger[0]['store_grade'],$storemanger[0]['store_id']);
            $g['profit'] = $g['sub_store_price']-$g['buy_price'];//收益
            $goods[$gk] = $g;
        }
        $result['goods'] = $goods;
        $result['coupon'] = $now_cart['object']['coupon'];
        if($storemanger[0]['store_grade']=='1'){
            $mdl_cur = app::get('ectools')->model('currency');
            $cur_us = $mdl_cur->getRow('*',array('cur_default'=>'false'));
            $result['cur_sign'] = $cur_us['cur_sign'];
            $result['cur_rate'] = $cur_us['cur_rate'];
            $result['cur_name'] = $cur_us['cur_name'];
        }
        return $this->apiData(true,array('cartlist'=>$result),200);
    }

    public function deletecart($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(!$member_id){
            return $this->apiData(false,null,301,app::get()->_('请登录'));
        }
        $mCartObject = app::get('b2c')->model('cart_objects');
        if($params['delcarts'] && is_array($params['delcarts'])){
            foreach ($params['delcarts'] as $k => $cart) {
                $flag = $mCartObject->remove_object($cart['obj_type'], $cart['obj_ident'], $msg);
                if(!$flag){
                    return $this->apiData(false,$cart,400,$msg);
                }
            }
        }
        $now_cart = app::get('b2c')->model('cart')->get_objects();
        //购物车显示项目数或者商品数
        $cart_show_type = app::get('site')->model('widgets_instance')->getRow('params',array('widgets_type'=>'index_cart'));
        if($cart_show_type['params']['cart_show_type']=='2'){
            $now_cart['_cookie']['CART_NUMBER'] = $now_cart['_cookie']['CART_COUNT'];
        }
        return $this->apiData(true,$now_cart['_cookie'],200,app::get('b2c')->_('删除成功！'));
    }

    public function updatenums($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(!$member_id){
            return $this->apiData(false,null,301,app::get()->_('请登录'));
        }
        $res = app::get('b2c')->model('cart_objects')->update_object('goods',$params['obj_ident'],array('quantity'=>$params['quantity']));
        if($res){
            $now_cart = app::get('b2c')->model('cart')->get_objects();
            $goods = $now_cart['object']['goods'];
            if(empty($goods)){
                return $this->apiData(false,null,400,app::get('b2c')->_('购物车为空'));
            }
            foreach ($goods as $gk => $gv) {
                $p = $gv['obj_items']['products'][0];
                $g['goods_id'] = $p['goods_id'];
                $g['product_id'] = $p['product_id'];
                $g['goods_type'] = $p['goods_type'];
                $g['bn'] = $p['bn'];
                $g['name'] = $p['name'];
                $g['buy_price'] = $p['price']['buy_price'];
                $g['mktprice'] = $p['price']['mktprice'];
                $g['thumbnail'] = $p['thumbnail'];
                $g['new_name'] = $p['new_name'];
                $g['url'] = $p['url'];
                $g['store'] = $p['store'];
                $g['quantity'] = $gv['quantity'];
                $g['store_id'] = $gv['store_id'];
                $g['store_name'] = $gv['store_name'];
                $g['shop_name'] = $gv['shop_name'];
                $g['obj_ident'] = $gv['obj_ident'];
                $g['obj_type'] = $gv['obj_type'];
                $goods[$gk] = $g;
            }
            $result['goods'] = $goods;
            $result['coupon'] = $now_cart['object']['coupon'];
            //购物车显示项目数或者商品数
            $cart_show_type = app::get('site')->model('widgets_instance')->getRow('params',array('widgets_type'=>'index_cart'));
            if($cart_show_type['params']['cart_show_type']=='2'){
                $now_cart['_cookie']['CART_NUMBER'] = $now_cart['_cookie']['CART_COUNT'];
            }
            return $this->apiData(true,array('cartlist'=>$result,'CART_COUNT'=>$now_cart['_cookie']['CART_COUNT'],'CART_NUMBER'=>$now_cart['_cookie']['CART_NUMBER'],'CART_TOTAL_PRICE'=>$now_cart['_cookie']['CART_TOTAL_PRICE']),200,app::get('b2c')->_('更新成功'));
        }else{
            return $this->apiData(false,null,400,app::get('b2c')->_('更新失败'));
        }
        // $_POST['modify_quantity'] = array($params['obj_ident']=>array('quantity'=>$params['quantity']));
        // $_POST['response_type'] = 'true';
        // $_POST[0] = 'goods';
        // kernel::single('b2c_ctl_site_cart')->update_cart_api($msg);
    }

    public function checkout($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(!$member_id){
            return $this->apiData(false,null,301,app::get()->_('请登录'));
        }
        $store_info = app::get('business')->model('storemanger')->getRow("*",array('account_id'=>$member_id));
        //查询用户收货地址信息
        $arrMember = $this->get_current_member();
        $objMem = app::get('b2c')->model('members');
        $obj_member_addrs = app::get('b2c')->model('member_addrs');
        $addr = array();
        $member_point = 0;
        $shipping_method = '';
        $shipping_id = 0;
        $arr_shipping_method = array();
        $payment_method = 0;
        $def_addr = 0;
        $arr_def_addr = array();
        $str_def_currency = $arrMember['member_cur'] ? $arrMember['member_cur'] : "";
        
        $addrlist = $obj_member_addrs->getList('*',array('member_id'=>$member_id));
        foreach($addrlist as $k=>$v){
            $area = array();
            $area = explode(':',$v['area']);
            $addrlist[$k]['region_id'] = $area[2];
            $area = explode('/',$area[1]);
            
            if(in_array($area[0],array('北京','天津','上海','重庆'))){
                $area[0] = '';
            }
            $addrlist[$k]['area_str'] = implode("",$area);
            if($v['def_addr']==1){
                $addr_default_addr = $addrlist[$k];
            }
        }
        if($addrlist){
            if(!$addr_default_addr){
                $addrlist[0]['def_addr'] = 1;
                $addr_default_addr = $addrlist[0];
            }
        }
        if(!empty($params['addr_id'])){
            foreach ($addrlist as $key => $addr) {
                if($addr['addr_id']==$params['addr_id']){
                    $addr_default_addr = $addr;
                    break;
                }
            }
        }
        $result['default_addr'] = $addr_default_addr;

        $flag = $this->_common(0,$error_msg,$res);
        if(!$flag){
            return $this->apiData(false,null,400,$error_msg);
        }

        $now_cart = $res['aCart'];
        if($res['is_empty'] && empty($now_cart['object']['goods'])){
            return $this->apiData(false,null,400,app::get('b2c')->_('购物车还没有数据'));
        }
        
        foreach ($now_cart['object']['goods'] as $goods) {
            //预售商品与普通商品和其他活动商品互斥  by zhuhao
            if($now_cart['prepare'] == 'true') {
                if(!isset($goods['act_type'])){
                    return $this->apiData(false,null,400,app::get('b2c')->_('预售商品不能与普通商品同时购买！'));
                }else if(isset($goods['act_type'])&&$goods['act_type']!='prepare'){
                    return $this->apiData(false,null,400,app::get('b2c')->_('预售商品不能其他活动商品同时购买！'));
                }
                
            }
            //团购商品与普通商品和其他活动商品互斥 
            if($now_cart['is_group'] == 'true') {
                if(!isset($goods['act_type'])){
                    return $this->apiData(false,null,400,app::get('b2c')->_('团购商品不能与普通商品同时购买！'));
                }else if(isset($goods['act_type'])&&$goods['act_type']!='group'){
                    return $this->apiData(false,null,400,app::get('b2c')->_('团购商品不能其他活动商品同时购买！'));
                }else if($goods['act_type']=='group'){
                    $goods = $this->pagedata['aCart']['object']['goods'];
                    if(isset($goods[$key+1]['act_id'])&&($goods[$key]['act_id']!=$goods[$key+1]['act_id'])){
                        return $this->apiData(false,null,400,app::get('b2c')->_('不能团购活动的商品不能同时加入购物车！'));
                    }
                }
            }
        }
        // 购物是否满足起订量和起订金额
        if ((isset($now_cart['cart_status']) && $now_cart['cart_status'] == 'false') && (isset($now_cart['cart_error_html']) && $now_cart['cart_error_html'] != "")){
            return $this->apiData(false,null,400,$this->pagedata['aCart']['cart_error_html']);
        }
        $goods = array();
        foreach ($now_cart['object']['goods'] as $key => $value) {
            foreach ($params['content'] as $gk => $gv) {
                if($gv['obj_ident'] == $value['obj_ident']){
                    $gv['new_name'] = $value['obj_items']['products'][0]['new_name'];
                    $gv['thumbnail'] = $value['obj_items']['products'][0]['thumbnail'];
                    $gv['subtotal_price'] = $value['subtotal_price'];
                    //预售商品价格处理
                    if($now_cart['prepare'] == 'true') {
                        $gv['subtotal_price'] = $value['subtotal'];
                    }
                    $gv['quantity'] = $value['quantity'];
                    $goods[] = $gv;
                }
            }
        }
        if(count($goods)!=count($params['content']) || count($goods)!=count($now_cart['object']['goods'])){
            //暂不处理未同步数据 只返回购物车中有的数据
            // return $this->apiData(false,null,400,app::get('b2c')->_('存在未同步商品，请同步后重试'));
        }
        //货币类型和默认货币
        $currency = app::get('ectools')->model('currency');
        $currencys = $currency->getList('cur_id,cur_code,cur_name');
        $arrDefCurrency = $currency->getDefault();
        //订单分单
        $total_amount = kernel::single("ectools_math")->number_minus(array($res['aCart']["subtotal"], $res['aCart']['discount_amount']));
        $shipmoney = 0;
        $split_order=kernel::single('b2c_cart_object_split')->split_order($this,$result['default_addr']['region_id'],$now_cart);
        foreach ($split_order as $split_k => $split_v) {
            $result['order_split_id'] = $split_k;
            foreach ($split_v['slips'] as $splits_k => $splits_v) {
                $result['slips_id'] = $splits_k;
                $result['shipping_id'] = key($splits_v['shipping']);
            }
        }

        foreach($split_order as $store_id=>$sgoods){
            foreach($sgoods['slips'] as $order_sp=>$order){
                foreach($order['shipping'] as $dkey=>$ship){
                    if($ship['default_type']=='true'){
                      //由于前台显示已经减去了抵扣。所以此处仍然要加上运费。
                      //$this->pagedata['aCart']['subtotal_store_good_price'][$store_id]+=$ship['money'];
                      
                      //$total_amount+=$ship['money'];

                      if($res['aCart']['store_free_shipping'][$store_id]==0 || $res['aCart']['prepare'] =='true'||$res['aCart']['is_group'] =='true'||$res['aCart']['inAct']=='true'||$res['aCart']['is_spike']=='true'){//优惠券免运费
                           // $res['discount'][$store_id]+=$ship['money'];
                           //$total_amount-=$ship['money'];
                      }else{
						  $total_amount+=$ship['money'];
                          $shipmoney += $ship['money'];
                      }
                      if($total_amount<=0){
                          $total_amount=0;
                      }
                    }
                }
            }
        }

        $result['split_order'] = urlencode(serialize($split_order));
        //支付方式
        $result['pay_app_id'] = 'deposit';//默认站内币
        $result['currency'] = $arrDefCurrency['cur_code'];
        $result['business_goods'] = urlencode($now_cart['business_goods']);
        $result['md5_cart_info'] = kernel::single("b2c_cart_objects")->md5_cart_objects();
        $result['goods'] = $goods;
        $result['coupon'] = $now_cart['object']['coupon'];
        $result['total'] = array_merge($now_cart['_cookie'],array('store_shipping_money'=>$shipmoney,'subtotal_price_store'=>$now_cart['subtotal_goods_price']));
        $result['total']['CART_TOTAL_PRICE'] = $result['total']['subtotal_price_store'];
        $result['total']['subtotal_price_store'] = $result['total_amount'] = $total_amount;
        if($_POST['sub_order_id']){
            $result['total']['CART_TOTAL_PRICE'] = 0;
            $result['total']['store_shipping_money'] = 0;
            $result['total']['subtotal_price_store'] = 0;
            $result['virtual_cart'] = $_POST['sub_order_id'];
        }
        if($store_info['store_grade']=='1'){
            $mdl_cur = app::get('ectools')->model('currency');
            $cur_us = $mdl_cur->getRow('*',array('cur_default'=>'false'));
            $result['total']['cur_sign'] = $cur_us['cur_sign'];
            $result['total']['cur_rate'] = $cur_us['cur_rate'];
            $result['total']['cur_name'] = $cur_us['cur_name'];
        }
        // print_r($result);
        return $this->apiData(true,$result,200);
    }

    /*
    *  购物车每个店铺的商品总金额
    */
    public function store_total(&$aCart){
        foreach((array)$aCart['object']['goods'] as $key=>$value){
            if($value['adjunct']){
                foreach($value['adjunct'] as $adv){
                    $adjunctTatole += $adv['subtotal'];
                }
            }
            $total[$value['store_id']][$value['obj_ident']] = $value['subtotal_prefilter_after']+$adjunctTatole;
            if($value['freight_bear']=='business'){
                $store_free_shipping[$value['store_id']][] = 0;
                $total_weight[$value['store_id']][] = '0';
            }else{
                $store_free_shipping[$value['store_id']][] = 1;
                $total_weight[$value['store_id']][] = $value['subtotal_weight'];
            }
        }
    
        foreach((array)$aCart['object']['package'] as $key=>$value){
            $total[$value['store_id']][$value['obj_ident']] = $value['subtotal_price'];
            $store_free_shipping[$value['store_id']][] = 1;
            $total_weight[$value['store_id']][] = $value['subtotal_weight'];
        }
  
        $arrMember = $this->get_current_member();
        if($total){
            foreach($total as $key=>$value){
                $total[$key] = array_sum($value);
                $total_weight[$key] = array_sum($total_weight[$key]);
                $store_free_shipping[$key] = array_sum($store_free_shipping[$key]);
                $store_id = ','.$key.",";
                $couInfo = app::get('b2c')->model('coupons')->getList('cpns_id',array('store_id|has'=>$store_id));
                //如果没有指定经销商则为平台发放的优惠券
                $nostoreCou = app::get('b2c')->model('coupons')->getList('cpns_id',array('ISNULL(store_id)'=>'1'));
                $couInfo = array_merge($couInfo,$nostoreCou);
                $cId = array();
                foreach($couInfo as $k=>$v){
                    $cId[] = $v['cpns_id'];
                }
                // 取到店铺优惠券的信息
                if ($arrMember['member_id']){
                    $oCoupon = app::get('b2c')->model('member_coupon');
                    $filter = array('member_id'=>$arrMember['member_id']);
                    $filter['disabled'] = 'false';
                    $filter['memc_isvalid'] = 'true';
                    $filter['cpns_id|in'] = $cId;
                    $aData[$key] = $oCoupon->_get_list('*', $filter);
                    if( is_array($aData[$key]) ) {
                        foreach( $aData[$key] as $_key => $_val ) {
                            if( $_val['memc_used_times'] ) unset($aData[$key][$_key]);
                        }
                    }
                }
                
                $this->pagedata['coupon_lists'] = $aData;
                $shipping[$key] = kernel::single('b2c_ctl_site_cart',app::get('b2c'))->get_store_shipping($key,$total_weight,$total,$store_free_shipping,$aCart);
                $shipmoney[$key] = $shipping[$key][0]['money'];
                $subtotal[$key] = $total[$key] + $shipping[$key][0]['money'];
            }
        }
        $this->pagedata['arr_shipp'] = $shipping;
        $aCart['subtotal_weight_store'] = $total_weight;
        $aCart['store_shipping_money'] = $shipmoney;
        $aCart['subtotal_price_store'] = $subtotal;
        $aCart['subtotal_store_good_price'] = $total;
        $aCart['subtotal_goods'] = $aCart['subtotal'];
        $aCart['subtotal_goods_price'] = $aCart['subtotal_price'];
        $aCart['store_free_shipping'] = $store_free_shipping;
    }

    public function store_coupons(&$aCart){
        if($aCart['promotion_solution']){
            $tmp_coupons = $aCart['object']['coupon'];
            foreach($aCart['promotion_solution'] as $value){
                foreach($value['order'] as $k=>$v){
                    if($v['store_id']){
                        $discount[$v['store_id']] = $v['amount']; 
                    }else{
                        //平台发的优惠券 根据分单信息找到上级
                        $t_store_id = $tmp_coupons[$k]['store_id'];
                        $discount[$t_store_id] = $v['amount'];
                    }
                }
            }
            foreach($aCart['object']['coupon'] as $key=>$value){
                $value['discount_amount'] = $discount[$value['store_id']];
                $coupons[$value['store_id']] = $value;
                $aCart['object']['coupon'][$key] = $value;
            }
            $aCart['store_count'] = $discount;
            $this->pagedata['discount'] = $discount;
            $this->pagedata['coupon'] = $coupons;
        }
    }

    private function _common($flag=0,&$err_msg,&$result)
    {
        // 获取购物车数据信息
        $aCart = app::get('b2c')->model('cart')->get_objects();

        $this->_item_to_disabled( $aCart,$flag ); //处理购物车删除项
        $this->store_total($aCart);//计算购物车总体数据
        $this->store_coupons($aCart);//优惠券信息
        $this->pagedata['aCart'] = $aCart;
        $this->pagedata['isfastbuy'] = $flag;
        if( $this->show_gotocart_button ) $this->pagedata['show_gotocart_button'] = 'true';

        if( $this->ajax_update === true ) {
            foreach(kernel::servicelist('b2c_cart_object_apps') as $object) {
                if( !is_object($object) ) continue;

                //应该判断是否实现了接口
                if( !method_exists( $object,'get_update_num' ) ) continue;
                if( !method_exists( $object,'get_type' ) ) continue;

                $this->pagedata['edit_ajax_data'] = $object->get_update_num( $aCart['object'][$object->get_type()],$this->update_obj_ident );
                if( $this->pagedata['edit_ajax_data'] ) {
                    $this->pagedata['edit_ajax_data'] = json_encode( $this->pagedata['edit_ajax_data'] );
                    if( $object->get_type()=='goods' ) {
                        $this->pagedata['update_cart_type_godos'] = true;
                        if( !method_exists( $object,'get_error_html' ) ) continue;
                        $this->pagedata['error_msg'] = $object->get_error_html( $aCart['object']['goods'],$this->update_obj_ident );
                    }
                    break;
                }
            }
        }

        // 购物车是否为空
        $this->pagedata['is_empty'] = app::get('b2c')->model('cart')->is_empty($aCart);
        //ajax_html 删除单个商品时触发
        if($this->ajax_html && app::get('b2c')->model('cart')->is_empty($aCart)) {
            $arr_json_data = array(
                'is_empty' => 'true',
                'number'=>array(
                    'cart_number'=>$this->pagedata['aCart']['_cookie']['CART_NUMBER'],
                    'cart_count'=>$this->pagedata['aCart']['_cookie']['CART_COUNT'],
                ),
            );
            $this->pagedata = $arr_json_data;
            $error_msg = app::get('b2c')->_('购物车为空');
            return false;
        }

        // 购物车数据项的render
        $this->pagedata['item_section'] = $this->mCart->get_item_render();

        // 购物车数据项的render
        $this->pagedata['item_goods_section'] = $this->mCart->get_item_goods_render();

        // 优惠信息项render
        $this->pagedata['solution_section'] = $this->mCart->get_solution_render();

        //未享受的订单规则
        $this->pagedata['unuse_rule'] = $this->mCart->get_unuse_solution_cart($aCart);

        if( !$this->checklogin($_POST['login_token']) ) {
            $this->pagedata['login'] = 'nologin';
        }

        $imageDefault = app::get('image')->getConf('image.set');
        $this->pagedata['defaultImage'] = $imageDefault['S']['default_image'];
        $result = $this->pagedata;
        return true;
    }

    private function _item_to_disabled( &$aCart,$flag ) {

        foreach( kernel::servicelist('b2c_cart_object_apps') as $object ) {
            if( !is_object($object) ) continue;
            $o[$object->get_type()] = $object;
        }

        $arr_cart_disabled_session = $_SESSION['cart_objects_disabled_item'];
        foreach( (array)$aCart['object'] as $_obj_type => $_arr_by_obj_type ) {
            $tmp = $arr_cart_disabled_session[$_obj_type];
            if( isset($arr_cart_disabled_session[$_obj_type]) ) {
                if( !$o[$_obj_type] ) continue;
                if( !method_exists( $o[$_obj_type],'apply_to_disabled' ) ) continue;
                $aCart['object'][$_obj_type] = $o[$_obj_type]->apply_to_disabled( $_arr_by_obj_type, $tmp, $flag );
                $_SESSION['cart_objects_disabled_item'][$_obj_type] = $tmp;
            } else {
                if( $flag )
                    unset($_SESSION['cart_objects_disabled_item'][$obj_type]);
            }
        }
    }

    /**
     * 订单上浮
     * @param
     * @return
     * @author hmg
     **/
    public function auto_generation_order($params,&$code,&$sub_msg) {
        $member_id = $this->checklogin($params['login_token']);
        if(!$member_id){
            return $this->apiData(false,null,301,app::get()->_('请登录'));
        }
        $order_id = $params['order_id'];
        $prepare =false;
        $is_group = false;
        $storeinfo = app::get('business')->model('storemanger')->getRow('store_id',array('account_id'=>$member_id));
        $objOrder = app::get('b2c')->model('orders');
        if(!empty($order_id)){
            $temps = $objOrder->getList('order_id',array('prepare_order_source'=>$order_id));
            if(count($temps)>0){
                return $this->apiData(false,null,400,app::get('b2c')->_('操作失败，已生成此订单！'));
            }
        }
        $aOrder = $objOrder->dump($order_id,'*');
        if($aOrder['order_type'] == 'preparesell'){
            $objPreOrder = app::get('preparesell')->model('prepare_order');
            $temp_order = $objPreOrder->getRow('*',array('order_id'=>$order_id, 'store_id'=>$storeinfo['store_id'], 'status'=>'true'));
            if($temp_order){
                $prepare = true;
                $_POST['virtual_cart'] = $order_id;
                $_POST['sub_order_id'] = $order_id;
                return $this->checkout($params);
            }else{
                return $this->apiData(false,null,400,app::get('b2c')->_('参数错误'));
            }
        }else if($aOrder['order_type'] == 'group'){
            $temp_order = $objOrder->getRow('*',array('order_id'=>$order_id, 'store_id'=>$storeinfo['store_id'], 'status'=>'active'));
            if($temp_order){
                $is_group = true;
                $_POST['virtual_cart'] = $order_id;
                $_POST['sub_order_id'] = $order_id;
                return $this->checkout($params);
            }else{
                return $this->apiData(false,null,400,app::get('b2c')->_('参数错误'));
            }
        }
    }
    
}